/**
 * 类名：奖品业务类
 * 备注：负责奖品业务逻辑。
 * 作者：rankin
 * 日期：2016/03/4
 */
var Page = require('../models/page');
var Prize = require('../models/prize');

module.exports = {
    list: function (req, res) {
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Prize().findForPage(obj, function (err, count, pageCount, datas) {
            if (err) {
            }
            var boxdatas = datas;
            page.pageCount = pageCount;
            res.render('prize/prize_list', {
                datas: boxdatas,
                page: page
            });
        })
    },
    to_create: function (req, res) {
        res.render('prize/prize_create');
    },
    do_create: function (req, res) {
        var name = req.body.name;
        var price = req.body.price;
        var imgurl = req.body.imgurl;
        var taobao_url = req.body.taobao_url;
        var wechat_productId = req.body.wechat_productId;
        new Prize({
            name: name, //商品名称
            price: price, //商品价格
            imgurl: imgurl, //商品图片
            taobao_url: taobao_url, //商品淘宝链接
            wechat_productId: wechat_productId //微信购买链接
        }).save();
        res.redirect('/list/list?num=1');
    },
    prize_order: function (req, res) {
        var prizeid = req.query.list;
        new Prize().findPrizeById(prizeid, function (datas) {
            res.render('prize/prize_order', {data: datas[0]});
        });
    },
    to_edit: function (req, res) {
        var prize_id = req.query.list;
        new Prize().findPrizeById(prize_id, function (datas) {
            res.render('prize/prize_edit', {prizedata: datas[0], id: prize_id});
        });
    },
    do_edit: function (req, res) {
        var prize_id = req.body.id;
        var name = req.body.name;
        var price = req.body.price;
        var imgurl = req.body.imgurl;
        var taobao_url = req.body.taobao_url;
        var wechat_productId = req.body.wechat_productId;
        new Prize().updatePrizeById(prize_id, name, price, imgurl, taobao_url, wechat_productId, function (err) {
            console.log(err);
        });
        res.redirect('/list/list?num=1');
    },
    remove_prize: function (req, res) {
        var prize = req.query.list;
        new Box().findAllBox(function (err, datas) {
            var count = 0;
            async.whilst(function () {
                return count < datas.length;
            }, function (callback) {
                var doors = datas[count].doors;
                var count1 = 0;
                async.whilst(function () {
                    return count1 < doors.length;
                }, function (callback1) {
                    if (doors[count1].prize_id) {
                        console.log(count1);
                        if (doors[count1].prize_id == prize) {
                            req.flash('error', '此商品已绑定箱子，不可删除.');
                            return res.redirect('/list/list?num=1');
                        }
                    }
                    count1++;
                    callback1();

                }, function (err) {
                    count++;
                    callback();
                });

            }, function (err) {
                new Prize().removeIdById(prize, function (err) {
                    if (err) {
                        req.flash('error', '删除失败,请重试.');
                        return res.redirect('/list/list?num=1');
                    } else {
                        req.flash('success', '删除成功.');
                        return res.redirect('/list/list?num=1');
                    }
                });
            });
            //req.flash('error', '...........');
            //return res.redirect('/list/list?num=1');
        });
    },
    uploadimg: function (req, res) {
        var data = JSON.parse(req.body.avatar_data);
        if (!data) {
            res.send(false);
        }
        var filename = req.files.avatar_file.name;
        var x = Math.round(data.x);
        var y = Math.round(data.y);
        var height = Math.round(data.height);
        var width = Math.round(data.width);
        var oldpath = data.oldpath;

        var path1 = './uploads/';
        var path2 = './public/images/list/';
        if (!fs.existsSync(path2)) {
            fs.mkdirSync(path2);
        }
        //res.send({
        //    state:200,
        //    message:'上传成功',
        //    result:'./public/uploads/'+filename
        //});
        gm(req.files.avatar_file.path).crop(width, height, x, y)
            .resize(320, 320)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write(path2 + filename, function (err) {
                if (!err) {
                    fs.unlinkSync(req.files.avatar_file.path);//删除upload目录下的文件
                    //console.log('删除图片111');
                    if (fs.existsSync('./public' + oldpath)) {
                        fs.unlinkSync('./public' + oldpath);//删除用户目录下的文件
                    }
                    res.send({
                        state: 200,
                        message: '上传成功',
                        result: '/images/list/' + filename
                    });
                }
            });
    }
};


